package com.bringspring.system.base.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bringspring.common.base.ActionResult;
import com.bringspring.common.base.ActionResultCode;
import com.bringspring.common.base.UserInfo;
import com.bringspring.common.base.vo.PaginationVO;
import com.bringspring.common.config.ConfigValueUtil;
import com.bringspring.common.database.model.JdbcPageMod;
import com.bringspring.common.database.model.dto.PreparedStatementDTO;
import com.bringspring.common.database.model.entity.DbLinkEntity;
import com.bringspring.common.database.util.ConnUtil;
import com.bringspring.common.database.model.DataSourceModel;
import com.bringspring.common.database.util.JdbcUtil;
import com.bringspring.common.exception.DataException;
import com.bringspring.common.util.*;
import com.bringspring.common.util.jscript.JScriptUtil;
import com.bringspring.common.util.jwt.JwtUtil;
import com.bringspring.common.util.wxutil.HttpUtil;
import com.bringspring.system.base.entity.DataInterfaceEntity;
import com.bringspring.system.base.mapper.DataInterfaceMapper;
import com.bringspring.system.base.model.dataInterface.DataInterfaceActionVo;
import com.bringspring.system.base.model.dataInterface.DataInterfacePage;
import com.bringspring.system.base.model.dataInterface.PaginationDataInterface;
import com.bringspring.system.base.service.DataInterfaceLogService;
import com.bringspring.system.base.service.DataInterfaceService;
import com.bringspring.system.base.service.DblinkService;
import com.bringspring.system.base.util.DbSensitiveConstant;
import lombok.Cleanup;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2021/3/12 15:31
 */
@Service
public class DataInterfaceServiceImpl extends ServiceImpl<DataInterfaceMapper, DataInterfaceEntity> implements DataInterfaceService {
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private DblinkService dblinkService;
    @Autowired
    private DataSourceModel dataSourceUtils;
    @Autowired
    private DataInterfaceLogService dataInterfaceLogService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ConfigValueUtil configValueUtil;

    @Override
    public List<DataInterfaceEntity> getList(PaginationDataInterface pagination, String dataType) {
        // 定义变量判断是否需要使用修改时间倒序
        boolean flag = false;
        QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
        //关键字
        if (!StringUtils.isEmpty(pagination.getKeyword())) {
            flag = true;
            queryWrapper.lambda().and(
                    t -> t.like(DataInterfaceEntity::getFullName, pagination.getKeyword())
                            .or().like(DataInterfaceEntity::getEnCode, pagination.getKeyword())
            );
        }
        //分类
        queryWrapper.lambda().eq(DataInterfaceEntity::getCategoryId, pagination.getCategoryId());
        // 类型
        if (StringUtils.isNotEmpty(dataType)) {
            queryWrapper.lambda().eq(DataInterfaceEntity::getDataType, dataType);
        }
        //排序
        queryWrapper.lambda().orderByAsc(DataInterfaceEntity::getSortCode)
                .orderByDesc(DataInterfaceEntity::getCreatorTime);
        if (flag) {
            queryWrapper.lambda().orderByDesc(DataInterfaceEntity::getLastModifyTime);
        }
        queryWrapper.lambda().select(DataInterfaceEntity::getId, DataInterfaceEntity::getCheckType, DataInterfaceEntity::getCreatorTime, DataInterfaceEntity::getDataType,
                DataInterfaceEntity::getEnCode, DataInterfaceEntity::getEnabledMark, DataInterfaceEntity::getFullName, DataInterfaceEntity::getSortCode,
                DataInterfaceEntity::getRequestMethod, DataInterfaceEntity::getRequestParameters);
        Page<DataInterfaceEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<DataInterfaceEntity> iPage = this.page(page, queryWrapper);
        return pagination.setData(iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public List<DataInterfaceEntity> getList() {
        QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DataInterfaceEntity::getEnabledMark, 1)
                .orderByAsc(DataInterfaceEntity::getSortCode)
                .orderByDesc(DataInterfaceEntity::getCreatorTime);
//        queryWrapper.lambda().in(DataInterfaceEntity::getRequestMethod, 3,6,7);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public DataInterfaceEntity getInfo(String id) {
        QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DataInterfaceEntity::getId, id);
        return this.getOne(queryWrapper);
    }
    public DataInterfaceEntity getInfoByCode(String code) {
        QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DataInterfaceEntity::getEnCode, code);
        return this.getOne(queryWrapper);
    }
    @Override
    public void create(DataInterfaceEntity entity) {
        if (entity.getId() == null) {
            entity.setId(RandomUtil.uuId());
            entity.setCreatorUserId(userProvider.get().getUserId());
            entity.setCreatorTime(DateUtil.getNowDate());
            entity.setLastModifyTime(DateUtil.getNowDate());
        }
        this.save(entity);
    }

    @Override
    public boolean update(DataInterfaceEntity entity, String id) throws DataException {
        entity.setId(id);
        entity.setLastModifyUserId(userProvider.get().getUserId());
        entity.setLastModifyTime(DateUtil.getNowDate());
        return this.updateById(entity);
    }

    @Override
    public void delete(DataInterfaceEntity entity) {
        this.removeById(entity.getId());
    }

    @Override
    public boolean isExistByFullName(String fullName, String id) {
        QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DataInterfaceEntity::getFullName, fullName);
        if (!StringUtils.isEmpty(id)) {
            queryWrapper.lambda().ne(DataInterfaceEntity::getId, id);
        }
        return this.count(queryWrapper) > 0 ? true : false;
    }

    @Override
    public boolean isExistByEnCode(String enCode, String id) {
        QueryWrapper<DataInterfaceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DataInterfaceEntity::getEnCode, enCode);
        if (!StringUtils.isEmpty(id)) {
            queryWrapper.lambda().ne(DataInterfaceEntity::getId, id);
        }
        return this.count(queryWrapper) > 0 ? true : false;
    }

    @Override
    public ActionResult infoToId(String id) {
        return infoToId(id, null, null);
    }

    @Override
    public ActionResult infoToIdPageList(String id, DataInterfacePage page) {
        DataInterfaceEntity entity = getInfo(id);
        String dataProcessing = null;
        if (Objects.nonNull(entity) && StringUtils.isNotEmpty(entity.getDataProcessing())) {
            dataProcessing = entity.getDataProcessing();
        }
        Map<String, Integer> mapPage = new HashMap<>();
        mapPage.put("currentPage", (int) page.getCurrentPage());
        mapPage.put("pageSize", (int) page.getPageSize());
        List<Map<String, Object>> dataList = new ArrayList<>();
        int total = 0;
        if ("1".equals(entity.getDataType())) {
            Object object = executeSql(entity, null, new HashMap<>(16), mapPage);
            if (object instanceof JdbcPageMod) {
                JdbcPageMod jdbcPageMod = (JdbcPageMod) object;
                dataList = jdbcPageMod.getDataList();
                total = jdbcPageMod.getTotalRecord();
            }
        } else {
            ActionResult result = infoToId(id, null, null);
            DataInterfaceActionVo actionVo = (DataInterfaceActionVo) result.getData();
            if (actionVo.getData() instanceof List) {
                dataList = (List<Map<String, Object>>) actionVo.getData();
                total = dataList.size();
            }
            dataList = PageUtil.getListPage((int) page.getCurrentPage(), (int) page.getPageSize(), dataList);
        }
        if (StringUtils.isNotEmpty(page.getKeyword())) {
            dataList = dataList.stream().filter(t -> page.getKeyword().equals(String.valueOf(t.get(page.getRelationField())))).collect(Collectors.toList());
        }
        PaginationVO pagination = JsonUtil.getJsonToBean(page, PaginationVO.class);
        pagination.setTotal(total);
        return ActionResult.page(dataList, pagination, dataProcessing);
    }

    @Override
    public Map<String, Object> infoToInfo(String id, DataInterfacePage page) {
        Map<String, Object> dataMap = new HashMap<>();
        ActionResult result = infoToId(id, null, null);
        DataInterfaceActionVo actionVo = (DataInterfaceActionVo) result.getData();
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (actionVo.getData() instanceof List) {
            dataList = (List<Map<String, Object>>) actionVo.getData();
        }
        if (StringUtils.isNotEmpty(page.getId())) {
            dataMap = dataList.stream().filter(t -> page.getId().equals(String.valueOf(t.get(page.getPropsValue())))).findFirst().orElse(new HashMap<>());
        }
        return dataMap;
    }

    @Override
    public ActionResult infoToId(String id, String tenantId, Map<String, String> map) {
        DataInterfaceEntity entity = this.getInfo(id);
        if (entity == null) {
            entity = new DataInterfaceEntity();
        }
        //判读验证类型
        int checkType = entity.getCheckType() != null ? entity.getCheckType() : 0;
        //鉴权验证
        if (checkType == 1) {
            //获取token
            String token = ServletUtils.getRequest().getHeader(Constants.AUTHORIZATION);
            if (StringUtils.isNotEmpty(token)) {
                String realToken = JwtUtil.getRealToken(token);
                if (!redisUtil.exists(realToken)) {
                    return ActionResult.fail(ActionResultCode.SessionOverdue.getMessage());
                }
            } else {
                return ActionResult.fail(ActionResultCode.SessionOverdue.getMessage());
            }
        }
        //跨域验证
        if (checkType == 2) {
            //跨域参数获取
            String ipAddress = StringUtils.isNotEmpty(entity.getIpAddress()) ? entity.getIpAddress() : "";
            String ipAddr = IpUtil.getIpAddr();
            String[] ips = ipAddress.split(",");
            boolean isCross = false;
            for (String ip : ips) {
                if (ip.equals(ipAddr)) {
                    isCross = true;
                }
            }
            if (!isCross) {
                return ActionResult.fail("跨域验证失败");
            }
        }
        //开始调用的时间
        LocalDateTime dateTime = LocalDateTime.now();
        //调用时间
        int invokWasteTime = 0;
        Object data = null;
        try {
            //如果是静态数据
            if (entity.getDataType() == 2) {
                try {
                    Map<String, Object> maps = JsonUtil.stringToMap(entity.getQuery());
                    //调用时间
                    invokWasteTime = invokTime(dateTime);
                    //添加调用日志
                    dataInterfaceLogService.create(id, invokWasteTime);
                    data=maps;
                } catch (Exception e) {
                    try {
                        List<Map<String, Object>> list = JsonUtil.getJsonToListMap(entity.getQuery());
                        //调用时间
                        invokWasteTime = invokTime(dateTime);
                        //添加调用日志
                        dataInterfaceLogService.create(id, invokWasteTime);
                        data=list;
                    } catch (Exception exception) {
                        Object obj = entity.getQuery() != null ? entity.getQuery() : null;
                        //调用时间
                        invokWasteTime = invokTime(dateTime);
                        //添加调用日志
                        dataInterfaceLogService.create(id, invokWasteTime);
                        data = obj;
                    }
                }
            } else if (entity.getDataType() == 3) {
                //HTTP调用或HTTPS调用
                JSONObject jsonObject = callHTTP(entity, map);
                //调用时间
                invokWasteTime = invokTime(dateTime);
                //添加调用日志
                dataInterfaceLogService.create(id, invokWasteTime);
                if (Objects.nonNull(jsonObject) && "1".equals(jsonObject.get("errorCode"))) {
                    return ActionResult.fail("外部接口暂时只支持HTTP和HTTPS方式");
                }
                // 判断返回参数长度和key是否跟内置的一致
                ActionResult actionResult = returnAction(jsonObject);
                data = JScriptUtil.callJs(entity.getDataProcessing(), Objects.nonNull(actionResult) ? actionResult.getData() : (jsonObject == null ? new ArrayList<>() : jsonObject));
            } else if (entity.getDataType() == 1) {
                if (Objects.isNull(map)) {
                    map = new HashMap<>(16);
                    List<Map<String, Object>> jsonToListMap = JsonUtil.getJsonToListMap(entity.getRequestParameters());
                    for (Map<String, Object> maps : jsonToListMap) {
                        if (Objects.nonNull(maps)) {
                            String field = String.valueOf(maps.get("field"));
                            String value = String.valueOf(maps.get("defaultValue"));
                            map.put(field, value);
                        }
                    }
                }
                for (String key : map.keySet()) {
                    map.put(key, "'" + map.get(key) + "'");
                }
                List<Map<String, Object>> SQLMapList = executeSql(entity, tenantId, map);
                //调用时间
                invokWasteTime = invokTime(dateTime);
                //添加调用日志
                dataInterfaceLogService.create(id, invokWasteTime);
                data = JScriptUtil.callJs(entity.getDataProcessing(), SQLMapList == null ? new ArrayList<>() : SQLMapList);
            }
        } catch (Exception e) {
            log.error("错误提示:" + e.getMessage());
            // 本地调试时打印出问题
            e.printStackTrace();
//            actionVo.setData(new ArrayList<>());
            return ActionResult.fail("接口请求失败");
        }
        return ActionResult.success(data);
    }

    @Override
    public ActionResult getApiByCode(String code, String tenantId, Map<String, String> map) {
        DataInterfaceEntity entity = this.getInfoByCode(code);
        if (entity == null) {
            entity = new DataInterfaceEntity();
        }
        //判读验证类型
        int checkType = entity.getCheckType() != null ? entity.getCheckType() : 0;
        //鉴权验证
        if (checkType == 1) {
            //获取token
            String token = ServletUtils.getRequest().getHeader(Constants.AUTHORIZATION);
            if (StringUtils.isNotEmpty(token)) {
                String realToken = JwtUtil.getRealToken(token);
                if (!redisUtil.exists(realToken)) {
                    return ActionResult.fail(ActionResultCode.SessionOverdue.getMessage());
                }
            } else {
                return ActionResult.fail(ActionResultCode.SessionOverdue.getMessage());
            }
        }
        //跨域验证
        if (checkType == 2) {
            //跨域参数获取
            String ipAddress = StringUtils.isNotEmpty(entity.getIpAddress()) ? entity.getIpAddress() : "";
            String ipAddr = IpUtil.getIpAddr();
            String[] ips = ipAddress.split(",");
            boolean isCross = false;
            for (String ip : ips) {
                if (ip.equals(ipAddr)) {
                    isCross = true;
                }
            }
            if (!isCross) {
                return ActionResult.fail("跨域验证失败");
            }
        }
        //开始调用的时间
        LocalDateTime dateTime = LocalDateTime.now();
        //调用时间
        int invokWasteTime = 0;
        Object data = null;
        try {
            String id = entity.getId();
            //如果是静态数据
            if (entity.getDataType() == 2) {
                try {
                    Map<String, Object> maps = JsonUtil.stringToMap(entity.getQuery());
                    //调用时间
                    invokWasteTime = invokTime(dateTime);
                    //添加调用日志
                    dataInterfaceLogService.create(id, invokWasteTime);
                    data=maps;
                } catch (Exception e) {
                    try {
                        List<Map<String, Object>> list = JsonUtil.getJsonToListMap(entity.getQuery());
                        //调用时间
                        invokWasteTime = invokTime(dateTime);
                        //添加调用日志
                        dataInterfaceLogService.create(id, invokWasteTime);
                        data=list;
                    } catch (Exception exception) {
                        Object obj = entity.getQuery() != null ? entity.getQuery() : null;
                        //调用时间
                        invokWasteTime = invokTime(dateTime);
                        //添加调用日志
                        dataInterfaceLogService.create(id, invokWasteTime);
                        data = obj;
                    }
                }
            } else if (entity.getDataType() == 3) {
                //HTTP调用或HTTPS调用
                JSONObject jsonObject = callHTTP(entity, map);
                //调用时间
                invokWasteTime = invokTime(dateTime);
                //添加调用日志
                dataInterfaceLogService.create(id, invokWasteTime);
                if (Objects.nonNull(jsonObject) && "1".equals(jsonObject.get("errorCode"))) {
                    return ActionResult.fail("外部接口暂时只支持HTTP和HTTPS方式");
                }
                // 判断返回参数长度和key是否跟内置的一致
                ActionResult actionResult = returnAction(jsonObject);
                data = JScriptUtil.callJs(entity.getDataProcessing(), Objects.nonNull(actionResult) ? actionResult.getData() : (jsonObject == null ? new ArrayList<>() : jsonObject));
            } else if (entity.getDataType() == 1) {
                if (Objects.isNull(map)) {
                    map = new HashMap<>(16);
                    List<Map<String, Object>> jsonToListMap = JsonUtil.getJsonToListMap(entity.getRequestParameters());
                    for (Map<String, Object> maps : jsonToListMap) {
                        if (Objects.nonNull(maps)) {
                            String field = String.valueOf(maps.get("field"));
                            String value = String.valueOf(maps.get("defaultValue"));
                            map.put(field, value);
                        }
                    }
                }
                for (String key : map.keySet()) {
                    map.put(key, "'" + map.get(key) + "'");
                }
                List<Map<String, Object>> SQLMapList = executeSql(entity, tenantId, map);
                //调用时间
                invokWasteTime = invokTime(dateTime);
                //添加调用日志
                dataInterfaceLogService.create(id, invokWasteTime);
                data = JScriptUtil.callJs(entity.getDataProcessing(), SQLMapList == null ? new ArrayList<>() : SQLMapList);
            }
        } catch (Exception e) {
            log.error("错误提示:" + e.getMessage());
            // 本地调试时打印出问题
            e.printStackTrace();
//            actionVo.setData(new ArrayList<>());
            return ActionResult.fail("接口请求失败");
        }
        return ActionResult.success(data);
    }
    @Override
    public Object preview(String id) {
        DataInterfaceActionVo actionVo = new DataInterfaceActionVo();
        try {
            DataInterfaceEntity entity = getInfo(id);
            if (entity != null) {
                JSONObject jsonObject = new JSONObject();
                String query = entity.getQuery();
                // 远端
                if (entity.getDataType() == 3) {
                    jsonObject = callHTTP(entity, null);
                    if (Objects.nonNull(jsonObject) && "1".equals(jsonObject.get("errorCode"))) {
                        jsonObject.put("errorCode", "1");
                        jsonObject.put("errorMsg", "外部接口暂时只支持HTTP和HTTPS方式");
                        return jsonObject;
                    }
                    // 判断返回参数长度和key是否跟内置的一致
                    ActionResult actionResult = returnAction(jsonObject);
                    if (Objects.nonNull(actionResult)) {
                        actionVo.setData(actionResult.getData());
                        return actionVo;
                    }
                    actionVo.setData(jsonObject);
                } else if (entity.getDataType() == 1) {
                    // 如果是SQL
                    // 判断是否有敏感词
                    String sensitive = DbSensitiveConstant.SENSITIVE;
                    String[] split = sensitive.split(",");
                    for (String str : split) {
                        boolean contains = query.toUpperCase().contains(str.trim());
                        if (contains) {
                            jsonObject.put("errorCode", "1");
                            jsonObject.put("errorMsg", "该SQL含有敏感字：" + str.trim());
                            return jsonObject;
                        }
                    }
                    // 组装自定义参数，取默认值
                    Map<String, String> map = null;
                    String requestParameters = entity.getRequestParameters();
                    if (StringUtils.isNotEmpty(requestParameters)) {
                        map = new HashMap<>(16);
                        List<Map<String, Object>> jsonToListMap = JsonUtil.getJsonToListMap(requestParameters);
                        // 组件map
                        for (Map<String, Object> maps : jsonToListMap) {
                            if (Objects.nonNull(maps)) {
                                String field = String.valueOf(maps.get("field"));
                                String value = String.valueOf(maps.get("defaultValue"));
                                map.put(field, "'" + value + "'");
                            }
                        }
                    }
                    List<Map<String, Object>> mapList = executeSql(entity, null, map);
                    actionVo.setData(mapList);
                } else {
                    actionVo.setData(entity.getQuery());
                }
                actionVo.setData(JScriptUtil.callJs(entity.getDataProcessing(), actionVo.getData()));
                return actionVo;
            }
        } catch (Exception e) {
            actionVo.setData(new ArrayList<>());
            log.error("预览发送错误：" + e.getMessage());
        }
        return actionVo;
    }

    /**
     * 执行SQL
     *
     * @param entity
     * @param tenantId
     * @param map
     * @return
     * @throws DataException
     */
    private List<Map<String, Object>> executeSql(DataInterfaceEntity entity, String tenantId, Map<String, String> map) throws Exception {
        DbLinkEntity linkEntity = dblinkService.getInfo(entity.getDbLinkId());
        String sql = entity.getQuery();
        @Cleanup Connection conn = null;
        UserInfo userInfo = userProvider.get();
        if (linkEntity != null) {
            conn = ConnUtil.getConn(linkEntity);
        } else {
            // 多租户条件下
            if (Boolean.parseBoolean(configValueUtil.getMultiTenancy())) {
                if (StringUtils.isNotEmpty(userInfo.getTenantId())) {
                    String dbName = userInfo.getTenantDbConnectionString();
                    DataSourceModel dataSourceUtils1 = dataSourceUtils;
                    dataSourceUtils1.setDbName(dbName);
                    conn = ConnUtil.getConn(dataSourceUtils1);
                } else {
                    // 如果未登录情况下
                    DataSourceModel dataSourceUtils1 = dataSourceUtils;
                    dataSourceUtils1.setDbName(tenantId);
                    conn = ConnUtil.getConn(dataSourceUtils1);
                }
            } else {
                // 非多租户条件下
                conn = ConnUtil.getConn(dataSourceUtils);
            }
        }
        StringBuffer stringBuffer = new StringBuffer();
        // 系统内置参数替换
        sql = systemParameter(sql, userInfo);
        // 自定义参数替换
        if (StringUtils.isNotEmpty(sql)) {
            StringSubstitutor strSubstitutor = new StringSubstitutor(map, "{", "}");
            sql = strSubstitutor.replace(sql);
        }
        stringBuffer.append(sql);
        if ("1".equals(entity.getRequestMethod()) || "2".equals(entity.getRequestMethod()) || "4".equals(entity.getRequestMethod())) {
            boolean flag = JdbcUtil.creUpDe(new PreparedStatementDTO(conn, stringBuffer.toString()));
            return new ArrayList<>();
        }
        return JdbcUtil.queryListAlias(new PreparedStatementDTO(conn, stringBuffer.toString()));
    }



    /**
     * 执行SQL
     *
     * @param entity
     * @param tenantId
     * @param map
     * @return
     * @throws DataException
     */
    private Object executeSql(DataInterfaceEntity entity, String tenantId, Map<String, String> map, Map<String, Integer> mapPage) {
        DbLinkEntity linkEntity = dblinkService.getInfo(entity.getDbLinkId());
        try {
            String sql = entity.getQuery();
            @Cleanup Connection conn = null;
            UserInfo userInfo = userProvider.get();
            if (linkEntity != null) {
                conn = ConnUtil.getConn(linkEntity);
            } else {
                // 多租户条件下
                if (Boolean.parseBoolean(configValueUtil.getMultiTenancy())) {
                    if (StringUtils.isNotEmpty(userInfo.getTenantId())) {
                        String dbName = userInfo.getTenantDbConnectionString();
                        DataSourceModel dataSourceUtils1 = dataSourceUtils;
                        dataSourceUtils1.setDbName(dbName);
                        conn = ConnUtil.getConn(dataSourceUtils1);
                    } else {
                        // 如果未登录情况下
                        DataSourceModel dataSourceUtils1 = dataSourceUtils;
                        dataSourceUtils1.setDbName(tenantId);
                        conn = ConnUtil.getConn(dataSourceUtils1);
                    }
                } else {
                    // 非多租户条件下
                    conn = ConnUtil.getConn(dataSourceUtils);
                }
            }
            StringBuffer stringBuffer = new StringBuffer();
            // 系统内置参数替换
            sql = systemParameter(sql, userInfo);
            // 自定义参数替换
            if (StringUtils.isNotEmpty(sql)) {
                StringSubstitutor strSubstitutor = new StringSubstitutor(map, "{", "}");
                sql = strSubstitutor.replace(sql);
            }
            stringBuffer.append(sql);
            if (Objects.nonNull(mapPage)) {
                JdbcPageMod jdbcPageMod = JdbcUtil.queryPage(new PreparedStatementDTO(conn, stringBuffer.toString()), "asc", mapPage.get("currentPage"), mapPage.get("pageSize"));
                return jdbcPageMod;
            }
            if ("1".equals(entity.getRequestMethod()) || "2".equals(entity.getRequestMethod()) || "4".equals(entity.getRequestMethod())) {
                boolean flag = JdbcUtil.creUpDe(new PreparedStatementDTO(conn, stringBuffer.toString()));
                return null;
            }
            return JdbcUtil.queryList(new PreparedStatementDTO(conn, stringBuffer.toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * HTTP调用
     *
     * @param entity
     * @return get
     */
    private JSONObject callHTTP(DataInterfaceEntity entity, Map<String, String> map) {
        JSONObject get = new JSONObject();
        // Post请求拼接参数
        JSONObject jsonObject = new JSONObject();
        String path = entity.getPath();
        // 请求方法
        String requestMethod = entity.getRequestMethod();
        //判断是否为http或https
        if ("https".equalsIgnoreCase(path.substring(0, 5)) || "http".equalsIgnoreCase(path.substring(0, 4))) {
            //请求参数解析
            List<Map<String, Object>> jsonToListMap = JsonUtil.getJsonToListMap(entity.getRequestParameters());
            if (jsonToListMap != null) {
                // 判断是否为get，get从url上拼接
                if ("6".equals(requestMethod)) {
                    path = !path.contains("?") ? path += "?" : path + "&";
                    if (Objects.nonNull(map)) {
                        for (String field : map.keySet()) {
                            String value = String.valueOf(map.get(field));
                            path = path + field + "=" + value.replaceAll("'", "") + "&";
                        }
                    } else {
                        path = parameterHandler(path, jsonToListMap);
                    }
                    requestMethod = "GET";
                } else {
                    // 判断是否使用默认值
                    if (Objects.nonNull(map)) {
                        for (String field : map.keySet()) {
                            String value = String.valueOf(map.get(field));
                            jsonObject.put(field, value);
                        }
                    } else {
                        for (Map<String, Object> maps : jsonToListMap) {
                            if (Objects.nonNull(maps)) {
                                String field = String.valueOf(maps.get("field"));
                                String value = String.valueOf(maps.get("defaultValue"));
                                jsonObject.put(field, value);
                            }
                        }
                    }
                    requestMethod = "POST";
                }
            }
            //获取token
            String token = UserProvider.getToken();
            String jsonObjects = jsonObject.size() > 0 ? jsonObject.toJSONString() : null;
            // 获取请求头参数
            String requestHeaders = entity.getRequestHeaders();
            if (StringUtils.isNotEmpty(requestHeaders)) {
                List<Map<String, Object>> requestHeader = JsonUtil.getJsonToListMap(requestHeaders);
                for (Map<String, Object> maps : requestHeader) {
                    if (Objects.nonNull(maps)) {
                        String field = String.valueOf(maps.get("field"));
                        String value = String.valueOf(maps.get("defaultValue"));
                        jsonObject.put(field, value);
                    }
                }
            }
            get = HttpUtil.httpRequest(path, requestMethod, jsonObjects, token, jsonObject != null ? JsonUtil.getObjectToString(jsonObject) : null);
            return get;
        } else {
            get.put("errorCode", "1");
            return get;
        }
    }

    /**
     * 处理参数
     *
     * @param path
     * @param jsonToListMap
     * @return
     */
    private String parameterHandler(String path, List<Map<String, Object>> jsonToListMap) {
        for (Map<String, Object> map : jsonToListMap) {
            if (map != null) {
                String field = String.valueOf(map.get("field"));
                String defaultValue = String.valueOf(map.get("defaultValue"));
                try {
                    defaultValue = URLEncoder.encode(defaultValue, "UTF-8");
                    path = path + field + "=" + defaultValue + "&";
                } catch (UnsupportedEncodingException e) {
                    log.error(e.getMessage());
                }
            }
        }
        return path;
    }

    /**
     * 处理sql参数
     *
     * @param sql
     * @return
     */
    private String systemParameter(String sql, UserInfo userInfo) {
        if (sql.contains("@user") && StringUtils.isNotEmpty(userInfo.getUserId())) {
            String userId = userInfo.getUserId();
            sql = sql.replaceAll("@user", "'" + userId + "'");
        }
        if (sql.contains("@department") && StringUtils.isNotEmpty(userInfo.getDepartmentId())) {
            String departmentId = userInfo.getDepartmentId();
            sql = sql.replaceAll("@department", "'" + departmentId + "'");
        }
        if (sql.contains("@organize") && StringUtils.isNotEmpty(userInfo.getOrganizeId())) {
            String organizeId = userInfo.getOrganizeId();
            sql = sql.replaceAll("@organize", "'" + organizeId + "'");
        }
        if (sql.contains("@postion") && StringUtils.isNotEmpty(userInfo.getPositionIds())) {
            String positionId = userInfo.getPositionIds() != null ? userInfo.getPositionIds()[0] : null;
            sql = sql.replaceAll("@postion", "'" + positionId + "'");
        }
        return sql;
    }

    /**
     * 判断如果是内部接口的话直接返回
     *
     * @param jsonObject
     * @return
     */
    private ActionResult returnAction(JSONObject jsonObject) {
        if (jsonObject.size() == 3 && jsonObject.get("code") != null && jsonObject.get("msg") != null && jsonObject.get("data") != null) {
            ActionResult result = JsonUtil.getJsonToBean(jsonObject, ActionResult.class);
            // code和msg存在则默认为内部接口
            if (Objects.nonNull(result) && result.getCode() != null && StringUtils.isNotEmpty(result.getMsg())) {
                return result;
            }
        }
        return null;
    }

    /**
     * 计算执行时间
     *
     * @param dateTime
     * @return
     */
    public int invokTime(LocalDateTime dateTime) {
        //调用时间
        int invokWasteTime = Integer.valueOf((int) (System.currentTimeMillis() - dateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli()));
        return invokWasteTime;
    }

}
